package com.azt.provider.impl;

import com.alibaba.fastjson.JSONArray;
import com.azt.api.enums.RoleTypeEnum;
import com.azt.api.enums.UserFuncShowTypeEnum;
import com.azt.api.pojo.Authority;
import com.azt.api.pojo.Company;
import com.azt.api.pojo.Role;
import com.azt.api.pojo.UserFunction;
import com.azt.api.service.FunctionService;
import com.azt.model.easy.EasyTree;
import com.azt.model.easy.EasyTreeModel;
import com.azt.provider.mapper.AuthorityMapper;
import com.azt.provider.mapper.RoleMapper;
import com.azt.provider.mapper.UserFunctionMapper;
import com.azt.service.EasyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class FunctionServiceImpl implements FunctionService {
	@Autowired
	private UserFunctionMapper userFunctionMapper;
	@Autowired
	private AuthorityMapper authorityMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private EasyService es;

	@Override
	public List<EasyTree> getFuncTree() {
		List<UserFunction> functionList = this.getAllParentFunction();
		EasyTreeModel model = new EasyTreeModel("id", "name", "children", "uri");
		Map<String, String> attributes = new HashMap<String, String>();
		attributes.put("ifFunction", "ifFunction");
		attributes.put("showType", "showType");
		attributes.put("funIcon", "funIcon");
		attributes.put("descr", "descr");
		attributes.put("code", "code");
		attributes.put("icon", "icon");
		model.setSortField("sortnum");
		model.setTypeField("type");
		model.setAttributes(attributes);
		return es.easyTree(functionList, model, null, true, true);
	}

	@Override
	public void saveOrUpdate(UserFunction ufunc) {
		if (ufunc.getId() != null) {
			userFunctionMapper.updateByPrimaryKeySelective(ufunc);
		} else {
			userFunctionMapper.insertSelective(ufunc);
		}
	}

	@Override
	public UserFunction getFuncById(Integer id) {
		return userFunctionMapper.getFuncById(id);
	}

	@Override
	public List<Authority> getAuthorityByRoleId(Integer roleId) {
		return authorityMapper.getAuthorityByRoleId(roleId);
	}

	@Override
	public List<Authority> getAuthorityByRoleIdAndFunc(Integer roleId, Map<String, Object> ParameterMap) {
		if (ParameterMap != null) {
			return authorityMapper.getAuthorityByRoleIdAndFunc(roleId, ParameterMap);
		} else {
			return this.getAuthorityByRoleId(roleId);
		}
	}

	@Override
	public List<UserFunction> getAllParentFunction() {
		return userFunctionMapper.getAllUserFunctionTree();
	}

	@Override
	public List<Authority> getAuthorityByUserId(Integer userId, Integer roleType) {
		List<Authority> authorityByRoleId = null;
		Role urole = roleMapper.getRoleByUserAndRoleType(userId, roleType);
		if (urole != null && urole.getId() != null) {
			authorityByRoleId = this.getAuthorityByRoleId(urole.getId());
		}
		return authorityByRoleId;
	}

	@Override
	public List<Authority> getAuthorityByUserIdAndFunc(Integer userId, Integer roleType,
			Map<String, Object> ParameterMap) {
		if (ParameterMap != null) {
			List<Authority> authorityByRoles = null;
			Role urole = roleMapper.getRoleByUserAndRoleType(userId, roleType);
			if (urole != null && urole.getId() != null) {
				authorityByRoles = this.getAuthorityByRoleIdAndFunc(urole.getId(), ParameterMap);
			}
			return authorityByRoles;
		} else {
			return this.getAuthorityByUserId(userId, roleType);
		}
	}

	@Override
	public UserFunction getFuncByParameterMap(Map<String, Object> ParameterMap) {
		return userFunctionMapper.getFuncByParameterMap(ParameterMap);
	}

	@Override
	public List<UserFunction> loadMenuTree(Company company, Role currentRole, int type, int showType) {
		// 首先查出所有符合条件的菜单
		List<UserFunction> allFuncList = null;
		if (showType == UserFuncShowTypeEnum.LEFT.getValue()) {// 左侧
			if (currentRole.getRoleType() == RoleTypeEnum.PURCHASER.getValue()
					|| currentRole.getRoleType() == RoleTypeEnum.PROVIDER.getValue()
					|| (company != null && company.getAuditState() != 3)) {
				// 获得全部菜单
				allFuncList = userFunctionMapper.findFuncByRoleId(currentRole.getId(), type, showType);
			}
			// 注册用户
			if (currentRole.getRoleType() == RoleTypeEnum.REGISTER.getValue()) {
				allFuncList = userFunctionMapper.findRegisterFunc(type, showType);
			}
		} else {// 头部是公共的
			allFuncList = userFunctionMapper.findFunc(type, showType);
		}

		// 根菜单
		List<UserFunction> fstFuncList = findFstFunc(allFuncList);
		for (UserFunction parent : fstFuncList) {
			// 开始递归获取子菜单(子菜单填充到fstFuncList中)
			loopFindChildFunc(allFuncList, parent);
		}
		return fstFuncList;
	}

	@Override
	public List<UserFunction> loadChildMenuTree(Company company, Role currentRole, Integer parentId) {
		UserFunction funcById = this.getFuncById(parentId);
		List<UserFunction> allFuncList = userFunctionMapper.loadChildMenuTree(parentId);// 查询子父的菜单

		// 我的消息菜单 特殊处理掉2左侧个菜单 2017.2.10改动
		if ("myMessage".equals(funcById.getCode())) {
			if (currentRole.getRoleType() == RoleTypeEnum.PURCHASER.getValue()) {
				Iterator it = allFuncList.iterator();
				while (it.hasNext()) {
					UserFunction tempobj = (UserFunction) it.next();
					if ("enquiryOptions".equals(tempobj.getCode())) {
						// 移除当前的对象
						it.remove();
					}
				}
			} else if (currentRole.getRoleType() == RoleTypeEnum.REGISTER.getValue()) {
				Iterator it = allFuncList.iterator();
				while (it.hasNext()) {
					UserFunction tempobj = (UserFunction) it.next();
					if (!"systemMessage".equals(tempobj.getCode()) && !"myMessage".equals(tempobj.getCode())) {// 根菜单不去除
						// 移除当前的对象
						it.remove();
					}
				}
			}
		}

		if ("accountSetting".equals(funcById.getCode())) {
			if (currentRole.getRoleType() == RoleTypeEnum.PROVIDER.getValue()) {
				Iterator it = allFuncList.iterator();
				while (it.hasNext()) {
					UserFunction tempobj = (UserFunction) it.next();
					if ("shippingAddress".equals(tempobj.getCode())) {
						// 移除当前的对象
						it.remove();
					}
				}
			} else if (currentRole.getRoleType() == RoleTypeEnum.PURCHASER.getValue()) {
				Iterator it = allFuncList.iterator();
				while (it.hasNext()) {
					UserFunction tempobj = (UserFunction) it.next();
					if ("enquiryOptions2".equals(tempobj.getCode())) {
						// 移除当前的对象
						it.remove();
					}
				}
			}
		}

		// 根菜单
		List<UserFunction> fstFuncList = findFstFunc(allFuncList);
		for (UserFunction parent : fstFuncList) {
			// 开始递归获取子菜单(子菜单填充到fstFuncList中)
			loopFindChildFunc(allFuncList, parent);
		}
		return fstFuncList;
	}

	/**
	 * 获取根级菜单
	 */
	private List<UserFunction> findFstFunc(List<UserFunction> list) {
		List<UserFunction> fstFuncList = new ArrayList<>();
		for (UserFunction function : list) {
			for (UserFunction function2 : list) {
				if (function.getId().equals(function2.getParentId()) || function.getParentId() == 0) {
					fstFuncList.add(function);
					break;
				}
			}
		}
		return fstFuncList;
	}

	/**
	 * 递归获取子菜单
	 */
	private void loopFindChildFunc(List<UserFunction> allFuncList, UserFunction parent) {
		for (UserFunction function : allFuncList) {
			if (function != null && function.getParentId() != null && function.getParentId().equals(parent.getId())) {
				parent.getChildren().add(function);
				loopFindChildFunc(allFuncList, function);
			}
		}
	}

	@Override
	public void delAuthorityByRoleId(Integer roleId) {
		Authority authority = new Authority();
		authority.setRoleId(roleId);
		authorityMapper.delete(authority);
	}

	@Override
	public void saveAuthority(Authority ua) {
		authorityMapper.insert(ua);
	}

	@Override
	public Authority createAuthority(Integer roleId, Integer functionId) {
		Authority author = new Authority();
		author.setRoleId(roleId);
		author.setFunctionId(functionId);
		this.saveAuthority(author);
		return author;
	}

	@Override
	public void createBranchAuthority(int roleId, Map<String, String[]> functionMap) {
		// 头部菜单不加入权限表了
		/*
		 * List<UserFunction> defaultMenuTree =
		 * this.findFunc(UserFuncTypeEnum.MENU.getValue(),UserFuncShowTypeEnum.
		 * TOP.getValue());
		 * 
		 * if(defaultMenuTree!=null && defaultMenuTree.size()>0){
		 * for(UserFunction fun:defaultMenuTree){ this.createAuthority(roleId,
		 * fun.getId()); } }
		 */

		if (functionMap != null) {

			Iterator entries = functionMap.entrySet().iterator();
			while (entries.hasNext()) {
				Map.Entry entry = (Map.Entry) entries.next();
				Integer parentFunctionId = Integer.parseInt(entry.getKey().toString());
				this.createAuthority(roleId, parentFunctionId);
				// JSONArray.fromObject(entry.getValue().toString()).toArray();
				JSONArray value = (JSONArray) entry.getValue();
				if (value != null && value.size() > 0) {
					for (Object childId : value) {
						this.createAuthority(roleId, Integer.parseInt(childId.toString()));
					}
				}
			}
		}
	}

	public List<UserFunction> findFunc(int type, int showType) {
		return userFunctionMapper.findFunc(type, showType);
	}

	@Override
	public List<UserFunction> findFuncByRoleId(int roleId, int type, int showType) {
		return userFunctionMapper.findFuncByRoleId(roleId, type, showType);
	}

	@Override
	public List<UserFunction> markTree(List<UserFunction> parentTree, List<UserFunction> branchTree) {
		// 必须是主功能 杨程说的分公司权限配置必须是主功能 去除非主功能
		List<UserFunction> parentTreeisf = new ArrayList();
		for (UserFunction pac : parentTree) {
			if (pac.getIfFunction() == 1) {
				parentTreeisf.add(pac);
			}
		}

		if (branchTree != null && branchTree.size() > 0) {
			for (UserFunction pac : parentTreeisf) {
				pac.setMark(0);// 初始化每个为未选择
				for (UserFunction bt : branchTree) {
					if (bt.getId().equals(pac.getId())) {
						pac.setMark(1);// 设置选择
					}
				}
			}
		}

		List<UserFunction> fstFuncList = this.findFstFunc(parentTreeisf);
		for (UserFunction parent : fstFuncList) {
			// 开始递归获取子菜单(子菜单填充到fstFuncList中)
			this.loopFindChildFunc(parentTreeisf, parent);
		}

		return fstFuncList;
	}

	@Override
	public UserFunction getParFunByCode(String menucode) {
		UserFunction fun = userFunctionMapper.getParFunByCode(menucode);
		if (fun != null) {
			if (fun.getParentId() != 0) {// 不是顶级菜单
				UserFunction func = this.getFuncById(fun.getParentId());
				return func;
			} else {
				return fun;
			}
		} else {
			return null;
		}
	}

	@Override
	public List<UserFunction> findAllFunc() {
		return userFunctionMapper.selectAll();
	}

}
